<html>
    <head>
        <title>- CSV Lines Import -</title>
    </head>
    <body>
        <form>
            <input type="file" name="F1" id="F1" size="80"><input type="button" value="Read" name="B1" id="B1" onclick="execFile()"><input type="reset" value="Reset" name="B2" id="B2" onclick="renderArea.innerHTML=''">
        </form>
        <div id="renderArea">
        </div>
        <script type="text/javascript" src="gears_init.js">
        </script>
        <script>
            // -- CSV PARSER --
            // author&nbsp; : Purbayu, 30Sep2008
            // email&nbsp;&nbsp; : purbayubudi@gmail.com
            //
            // description :
            //&nbsp; This jscript code describes how to load csv file and parse it into fields.
            //&nbsp; Additionally, a function to display html table as result is added.
            //
            // disclamer:
            //&nbsp; To use this code freely, you must put author's name in it.
            var db;
            //LoadXPIE();
            init();
            var renderArea = document.getElementById("renderArea");
            
            function execFile(){
                // main function to open, parse, and then render
                var myfile = document.getElementById("F1");
                
                // verify file extension (csv or not)
                if (myfile.value.match(/\.csv$/gi) == ".csv") {
                    // create progress window..
                    
                    /*
                     var progressWindow = window.open("","","top=10,left=10,height=100,width=200");
                     progressWindow.document.write("<html><head></head><body><div id='progressArea'></div></body></html>");
                     var progressArea = progressWindow.document.getElementById("progressArea");
                     */
                    // load csv file and split it line by line
                    var arr = readCSV(myfile.value);
                    var di = new Number(arr.length);
					/*di = di/4;
					
                    // parse csv line by line, start at 1 to skip header
                    for (var i = 1; i < di; i++) {
                        arr[i] = parseLineCSV(arr[i]);
						
                        renderArea.innerHTML = "Status: " + i + "/" + arr.length;
                        //progressArea.innerHTML="Parsing: "+(i+1)+" of "+arr.length;
                    }
					
					 for (var i = di; i < di*2; i++) {
                        arr[i] = parseLineCSV(arr[i]);
						
                        renderArea.innerHTML = "Status: " + i + "/" + arr.length;
                        //progressArea.innerHTML="Parsing: "+(i+1)+" of "+arr.length;
                    }
					
					for (var i = di*2; i < di*3; i++) {
                        arr[i] = parseLineCSV(arr[i]);
						
                        renderArea.innerHTML = "Status: " + i + "/" + arr.length;
                        //progressArea.innerHTML="Parsing: "+(i+1)+" of "+arr.length;
                    }
					*/
					for (var i = 1; i < arr.length; i++) {
                        arr[i] = parseLineCSV(arr[i]);
						
                        renderArea.innerHTML = "Status: " + i + "/" + arr.length;
                        //progressArea.innerHTML="Parsing: "+(i+1)+" of "+arr.length;
                    }
					
					alert('Done');
                    return;
                    // render the result into html table
					
					
                    s = '<table border=1>';
                    for (var i = 0; i < arr.length; i++) {
                        s = s + '<tr>';
                        for (var j = 0; j < arr[i].length; j++) {
                            s = s + '<td><font size="1" face="Verdana">' + arr[i][j] + '</font></td>';
                        }
                        //progressArea.innerHTML="Table rendering: "+(i+1)+" of "+arr.length;
                        s = s + '</tr>';
                    }
                    s = s + '</table>';
                    
                    // close progress window after all tasks are completed
                    // progressWindow.close();
                }
                else {
                    // show this if user tries to open non csv file
                    s = '<b><font size="1" face="Verdana" color="#FF0000">Not a CSV file!</font></b>';
                }
                
                renderArea.innerHTML = s;
            }
            
            //The following code is depicted from Professional Javascript for
            // Web Developers, a book by Nicholas C.Zakas
            /*
             if (typeof XMLHttpRequest == "undefined" && window.ActiveXObject) {
             function XMLHttpRequest() {
             var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
             "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
             "Microsoft.XMLHTTP"];
             for (var i=0; i < arrSignatures.length; i++) {
             try {
             var oRequest = new ActiveXObject(arrSignatures[i]);
             return oRequest;
             } catch (oError) {
             //ignore
             }
             }
             throw new Error("MSXML is not installed on your system.");
             }
             }
             */
            function init(){
                var success = false;
                
                if (window.google && google.gears) {
                    try {
                        db = google.gears.factory.create('beta.database');
                        
                        if (db) {
                            db.open('psdb');
                        }
                        
                    } 
                    catch (ex) {
                    }
                }
            }
            
            function readCSV(locfile){
                // load a whole csv file, and then split it line by line
                
                if (window.XMLHttpRequest) {
                    xhttp = new XMLHttpRequest();
                }
                else {
                    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xhttp.open("GET", locfile, false);
                
                xhttp.send("");
                xmlDoc = xhttp.responseXML;
                
                /*
                 if (window.XMLHttpRequest)
                 req = new XMLHttpRequest();
                 alert('here');//req.responseXML);
                 req.open("GET",locfile,false);
                 req.send("");*/
                return xhttp.responseText.split(/\n/g);
            }
            
            function parseLineCSV(lineCSV){
                // parse csv line by line into array
                var CSV = new Array();
                
                // Insert space before character ",". This is to anticipate 'split' in IE
                // try this:
                //
                // var a=",,,a,,b,,c,,,,d";
                // a=a.split(/\,/g);
                // document.write(a.length);
                //
                // You will see unexpected result!
                //
                
                //lineCSV = lineCSV.replace(/,/g," ,");
                
				var dbSaleName = "Sale_2009";
				var dbSalePaymentName = "SalePayment_2009";
				var dbSaleItemName ="SaleItem_2009";
				
                lineCSV = lineCSV.split(/;/g);
                
				
                var saleidT = lineCSV[0];
			    var LineID = lineCSV[1];
			    var ProductID = lineCSV[2];
				
				if (ProductID > 0) {
					
					var Price = lineCSV[3];
					var Qty = lineCSV[4];
					 db.execute('Insert into ' + dbSaleItemName + ' (id,saleid,itemid,description,qty,cost,price,taxes) values (?,?,?,?,?,?,?,?)',
				 [LineID, saleidT, ProductID, '',Qty, 0.00, Price, 0.00]);
				 query = 'Update ' + dbSaleItemName + ' set description=(select description from product where itemid=id),cost=(select cost from product where itemid=id) where itemid=?;';
				// document.getElementById("renderArea").innerHTML = query;
    				db.execute(query,[ProductID]) 
			   }
				else {
					var Paymethod = lineCSV[5];
					var Amount = lineCSV[6];
					 //payment
				 db.execute('Insert into ' + dbSalePaymentName + ' (id,saleid,paytype,amount) values (?,?,?,?)',
				  [LineID, saleidT, Paymethod, Amount]);
				  
				}
			    
				//line
                //TransactionID;LineID;ProductID;Price;Qty;Paymethod;Amount
               	
			        
                return CSV;
            }
			
			 //loads/imports xml data
                        function LoadCity(zipcode){
                            if (window.XMLHttpRequest) {
                                xhttp2 = new XMLHttpRequest()
                            }
                            else {
                                xhttp2 = new ActiveXObject("Microsoft.XMLHTTP")
                            }
                            
                            xhttp2.open("GET", "cities.xml", false);
                            xhttp2.send("");
                            xmlDoc2 = xhttp2.responseXML;
                            
                            var y = xmlDoc2.getElementsByTagName("cities");
                            for (i = 0; i < y.length; i++) {
                                x = y[i].childNodes; //a specific city
                                if (x[1].childNodes[0].nodeValue == zipcode) //check if matches an id
                                {
                                    return x[3].childNodes[0].nodeValue;
                                }
                            }
                        }
        </script>
    </body>
</html>
